# include "h.h"

// fft the data, then get the median frequency
int muscle_fatigue(float *data,int len, int fs)
{
    int N=(int) ceil(log2(len));
    int len2=(int) pow(2,N);
    int medfreq;
    TYPE_FFT *temp=calloc(len2,sizeof(TYPE_FFT));
    zeropadding(data,len,temp,len2);
    fft(temp,len2);
    
    medfreq=(medianfreq(temp,len2)+1)*fs/len2;
    free(temp);
    temp = NULL;
    return medfreq;
}

int medianfreq(TYPE_FFT *freqspe,int len)
{
    int i;
    float sum=0;
    float sum1=0;
    int med_freq=0;
    for(i=0;i<len/2;i++)
    {
        sum=sum+sqrtf(powf(freqspe[i].real,2)+powf(freqspe[i].imag,2));
    }
    
    for (i=0;i<len/2;i++)
    {
        sum1=sum1+sqrtf(powf(freqspe[i].real,2)+powf(freqspe[i].imag,2));
        if (sum1>sum/2)
        {
            med_freq=i;
            break;
        }
    }
    return med_freq;
} 

